using Intelli.Cust.Service.mvc.Models;
using Newtonsoft.Json;
using System.Text;

namespace Intelli.Cust.Service.mvc.Services
{
    public class IntelligentCustomerServiceClient : IIntelligentCustomerServiceClient
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<IntelligentCustomerServiceClient> _logger;
        private readonly string _baseUrl;

        public IntelligentCustomerServiceClient(HttpClient httpClient, ILogger<IntelligentCustomerServiceClient> logger, IConfiguration configuration)
        {
            _httpClient = httpClient;
            _logger = logger;
            _baseUrl = configuration["ApiSettings:BaseUrl"] ?? "http://localhost:5035";
        }

        public async Task<ChatResponse> SendMessageAsync(ChatRequest request)
        {
            try
            {
                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync($"{_baseUrl}/api/IntelligentCustomerService/chat", content);
                
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<ChatResponse>(responseContent) ?? new ChatResponse();
                }
                else
                {
                    _logger.LogError("API调用失败: {StatusCode}, {ReasonPhrase}", response.StatusCode, response.ReasonPhrase);
                    return new ChatResponse
                    {
                        Content = "抱歉，服务暂时不可用，请稍后重试。",
                        ErrorMessage = $"API调用失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送消息时发生错误");
                return new ChatResponse
                {
                    Content = "抱歉，发生网络错误，请检查网络连接。",
                    ErrorMessage = ex.Message
                };
            }
        }

        public async Task<List<ChatMessage>> GetConversationHistoryAsync(string sessionId, int limit = 10)
        {
            try
            {
                var response = await _httpClient.GetAsync($"{_baseUrl}/api/IntelligentCustomerService/history/{sessionId}?limit={limit}");
                
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    var history = JsonConvert.DeserializeObject<List<dynamic>>(content);
                    
                    var chatMessages = new List<ChatMessage>();
                    foreach (var item in history ?? new List<dynamic>())
                    {
                        chatMessages.Add(new ChatMessage
                        {
                            Id = item.id?.ToString() ?? Guid.NewGuid().ToString(),
                            Content = item.userInput?.ToString() ?? "",
                            IsUser = true,
                            Timestamp = item.timestamp != null ? DateTime.Parse(item.timestamp.ToString()) : DateTime.Now,
                            UserId = item.userId?.ToString(),
                            SessionId = item.sessionId?.ToString()
                        });

                        if (item.assistantResponse != null)
                        {
                            chatMessages.Add(new ChatMessage
                            {
                                Id = Guid.NewGuid().ToString(),
                                Content = item.assistantResponse.ToString(),
                                IsUser = false,
                                Timestamp = item.timestamp != null ? DateTime.Parse(item.timestamp.ToString()) : DateTime.Now,
                                UserId = item.userId?.ToString(),
                                SessionId = item.sessionId?.ToString()
                            });
                        }
                    }
                    
                    return chatMessages.OrderBy(m => m.Timestamp).ToList();
                }
                
                return new List<ChatMessage>();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取对话历史时发生错误");
                return new List<ChatMessage>();
            }
        }

        public async Task<bool> RateResponseAsync(string sessionId, string messageId, int rating, string? feedback = null)
        {
            try
            {
                var request = new
                {
                    sessionId,
                    messageId,
                    rating,
                    feedback
                };
                
                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync($"{_baseUrl}/api/IntelligentCustomerService/rate", content);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "评价回复时发生错误");
                return false;
            }
        }

        public async Task<bool> InitializeKnowledgeBaseAsync()
        {
            try
            {
                var response = await _httpClient.PostAsync($"{_baseUrl}/api/IntelligentCustomerService/knowledge/initialize", null);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化知识库时发生错误");
                return false;
            }
        }

        public async Task<bool> AddKnowledgeDocumentAsync(string document, Dictionary<string, object> metadata)
        {
            try
            {
                var request = new
                {
                    document,
                    metadata
                };
                
                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync($"{_baseUrl}/api/IntelligentCustomerService/knowledge/document", content);
                return response.IsSuccessStatusCode;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加知识库文档时发生错误");
                return false;
            }
        }
    }
} 